<?php

namespace App\Http\Controllers\Admin;

use App\Models\Cate as CateInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Cate extends Controller
{
    //栏目列表
    public function all ()
    {
        //时间可以用latest(),默认的就是areated_at排序
        $cates = (new CateInfo)->orderBy('sort','desc')->latest()->paginate(10);
        $data = [
            'cates' => $cates,
        ];
        return view('admin.cate.list',$data);
    }

    //栏目添加
    public function add ()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['sort','catename']);
            $result = (new CateInfo)->add($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => "添加成功",
                    'url' => url('admin/catelist'),
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg;
        }
        return view('admin.cate.add');
    }

    //栏目编辑
    public function edit ()
    {
        if (request()->isMethod('post')) {
           
            $data = request()->only(['id','sort','catename']);
            $result = (new CateInfo)->edit($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => "编辑成功",
                    'url' => url('admin/catelist')
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result,
                ];
            }
            return $msg;
        }
        $id = request()->route('id');
        $cates = (new CateInfo)->find($id);
        $data = [
            'cates' => $cates,
        ];
        return view('admin.cate.edit',$data);
    }

    //栏目删除
    public function del ()
    {
        $cates = CateInfo::find(request('id'));
        $result = $cates->delete();
        if ($result) {
            $msg = [
                'code' => 1,
                'msg' => "删除成功",
                'url' => url('admin/catelist'),
            ];
        } else {
            $msg = [
                'code' => 0,
                'msg' => "删除失败"
            ];
        }
        return $msg;
    }

    //栏目排序
    public function sort ()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['sort','id']);
            $result = (new CateInfo)->sort($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => "排序成功",
                    'url' => url('admin/catelist'),
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
    }
}
